<template>
  <div>
    <el-dialog title="选择数据字典" :visible="visible" width="400px" append-to-body @close="close">
      <el-input v-model="searchValue" placeholder="请输入字典名称按回车进行搜索" @keyup.enter.native="query" />

      <el-tree
        ref="tree"
        :data="treeData"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        :filter-node-method="filterNode"
        @current-change="handleTreeSelectChange"
      />

      <span>
        已选中：
        <el-input v-model="selectedName" readonly style="color:mediumblue" />
      </span>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button @click="close">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    return {
      visible: false,
      treeData: [],
      searchValue: '',
      defaultExpandedKeys: [],
      selectedValue: '',
      selectedName: ''
    }
  },
  created() {
    this.loadTree()
  },
  methods: {
    show() {
      // 此处强制调用重新加载数据，否则新添加或修改的数据不会生效
      this.loadTree()
      this.searchValue = ''
      this.visible = true
    },
    loadTree() {
      this.$api.system.dictionaryType.tree()
        .then(res => {
          this.treeData = res.data
          // 默认展开根节点
          this.defaultExpandedKeys.push(this.treeData[0].id)
        })
    },
    close() {
      this.visible = false
    },
    confirm() {
      this.$emit('ok', this.selectedValue, this.selectedName)
      this.visible = false
    },
    // 树节点选中改变
    handleTreeSelectChange(data) {
      this.selectedValue = data.id
      this.selectedName = data.label
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 树节点过滤
    query() {
      this.$refs.tree.filter(this.searchValue)
    }
  }
}

</script>

<style scoped>
</style>
